package controllers

import (
	"beego/comm/db"
	"beego/comm/entity"
	"beego/comm/requests"
	"beego/comm/source"
	"beego/comm/str"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"sync"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type FoodTypeController struct {
	beego.Controller
}

var (
	lockAddFoodType sync.Mutex
)

func (c *FoodTypeController) AddFoodType() {
	defer func() {
		err := recover()
		if nil != err {
			c.Data["json"] = map[string]interface{}{
				"add":       false,
				"errorInfo": err,
			}
			c.ServeJSON()
		}
	}()
	var food entity.Food
	json.Unmarshal(c.Ctx.Input.RequestBody, &food)
	food_name := food.Name
	user_name := food.UserName
	user_loginID := food.LoginID
	loginID, err := db.RedisGet("login-" + user_name)
	if nil != err {
		panic(fmt.Sprintf("%s", err.Error()))
	}
	if "" == loginID || loginID != user_loginID {
		panic("请先登录")
	}
	o := orm.NewOrm()
	var maps []orm.Params
	res_data := map[string]string{
		"food": food_name,
	}
	resp_data := requests.Post(source.Src.GetFlaskUrl()+"/food", res_data)
	var resp_data_stc map[string]map[string]string
	json.Unmarshal([]byte(resp_data), &resp_data_stc)
	lockAddFoodType.Lock()
	o.Raw(`select cur_id from sequence where table_name = 'food_list'`).Values(&maps)
	cur_id, _ := strconv.ParseInt(maps[0]["cur_id"].(string), 10, 64)
	var food_items = map[string]interface{}{
		"sql": make([]string, 0),
		"len": 0,
	}
	for k_food, v_compt := range resp_data_stc {
		if "error" == k_food {
			break
		}
		cur_id_tmp := fmt.Sprintf("%d", cur_id)
		var food_item = map[string]interface{}{
			"food_id":          cur_id_tmp,
			"food_name":        k_food,
			"food_composition": v_compt,
			"source":           "fq.chinafcd.org",
		}
		food_items = str.GenInsertSql(food_items, food_item, "food_list")
		cur_id += 1
	}
	data_sql, _ := food_items["sql"].([]string)
	for _, food_item_v := range data_sql {
		exe_result, err := o.Raw(food_item_v).Exec()
		beego.Info(fmt.Sprintf("insert执行结果: %s", exe_result))
		beego.Info(fmt.Sprintf("执行状态: %s", err))
	}
	cur_id_d := fmt.Sprintf("%d", cur_id)
	sql := `update sequence set cur_id = "` + cur_id_d + `" where table_name = 'food_list'`
	beego.Info(sql)
	exe_result, err := o.Raw(sql).Exec()
	beego.Info(fmt.Sprintf("delete执行结果: %s", exe_result))
	beego.Info(fmt.Sprintf("执行状态: %s", err))
	lockAddFoodType.Unlock()
	c.Data["json"] = map[string]interface{}{
		"add":       true,
		"errorInfo": "",
	}
	c.ServeJSON()
}

func (c *FoodTypeController) QueryFoodType() {
	defer func() {
		err := recover()
		if nil != err {
			c.Data["json"] = map[string]interface{}{
				"foodList":  nil,
				"errorInfo": err,
			}
			c.ServeJSON()
		}
	}()
	var food entity.Food
	json.Unmarshal(c.Ctx.Input.RequestBody, &food)
	food_name := food.Name
	user_name := food.UserName
	user_loginID := food.LoginID
	loginID, err := db.RedisGet("login-" + user_name)
	if nil != err {
		panic(fmt.Sprintf("%s", err.Error()))
	}
	if "" == loginID || loginID != user_loginID {
		panic("请先登录")
	}
	sql := "select food_name from food_list"
	food_name = strings.Trim(food_name, " ")
	if "" != food_name {
		sql += "where food_name like '%" + food_name + "%'"
	}
	o := orm.NewOrm()
	var maps []orm.Params
	o.Raw(sql).Values(&maps)
	var food_list []string
	for i := 0; i < len(maps); i++ {
		food_list = append(food_list, string(maps[i]["food_name"].(string)))
	}
	c.Data["json"] = map[string]interface{}{
		"foodList":  food_list,
		"errorInfo": "",
	}
	c.ServeJSON()
}

func (c *FoodTypeController) QueryFoodTypeDetail() {
	defer func() {
		err := recover()
		if nil != err {
			c.Data["json"] = map[string]interface{}{
				"count":     0,
				"foodList":  nil,
				"errorInfo": err,
			}
			c.ServeJSON()
		}
	}()
	var food entity.FoodDetailQuery
	json.Unmarshal(c.Ctx.Input.RequestBody, &food)
	food_name := food.Name
	user_name := food.UserName
	user_loginID := food.LoginID
	loginID, err := db.RedisGet("login-" + user_name)
	if nil != err {
		panic(fmt.Sprintf("%s", err.Error()))
	}
	if "" == loginID || loginID != user_loginID {
		panic("请先登录")
	}
	sql := "select food_id as id, food_name, food_composition from food_list"
	sql_count := "select count(1) as count from food_list"
	food_name = strings.Trim(food_name, " ")
	if "" != food_name {
		sql += "where food_name like '%" + food_name + "%'"
		sql_count += "where food_name like '%" + food_name + "%'"
	}
	o := orm.NewOrm()
	var maps []orm.Params
	o.Raw(sql_count).Values(&maps)
	count_f, _ := strconv.ParseInt(maps[0]["count"].(string), 10, 64)
	count := int(count_f)
	o.Raw(sql+` order by datetime desc, food_id desc limit ?, ?`).
		SetArgs(food.From, food.Page).Values(&maps)
	c.Data["json"] = map[string]interface{}{
		"count":     count,
		"foodList":  maps,
		"errorInfo": "",
	}
	c.ServeJSON()
}
